//
//  NSTools.m
//  Fotile
//
//  Created by xtmac on 23/2/16.
//  Copyright © 2016年 xtmac. All rights reserved.
//

#import "NSTools.h"
#import <CommonCrypto/CommonDigest.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

@implementation NSTools

+(NSString *)dataToHex:(NSData *)data{
    NSMutableString *hex = [NSMutableString string];
    const unsigned char *hexChar = data.bytes;
    for (NSUInteger i = 0; i < data.length; i++) {
        [hex appendFormat:@"%02X", hexChar[i]];
    }
    return [NSString stringWithString:hex];
}
//压缩图片
+ (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    
    // 设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}
+(NSData *)hexToData:(NSString *)hexString{
    NSUInteger len = hexString.length / 2;
    const char *hexCode = [hexString UTF8String];
    char * bytes = (char *)malloc(len);
    
    char *pos = (char *)hexCode;
    for (NSUInteger i = 0; i < hexString.length / 2; i++) {
        sscanf(pos, "%2hhx", &bytes[i]);
        pos += 2 * sizeof(char);
    }
    
    NSData * data = [[NSData alloc] initWithBytes:bytes length:len];
    
    free(bytes);
    return data;
}

+(CalendarDate)dateToCalendar:(NSDate *)date{
    NSCalendar *cal = [NSCalendar currentCalendar];
    unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dd = [cal components:unitFlags fromDate:date];
    CalendarDate calendarDate;
    calendarDate.year = [dd year];
    calendarDate.month = [dd month];
    calendarDate.day = [dd day];
    calendarDate.hour = [dd hour];
    calendarDate.minute = [dd minute];
    calendarDate.second = [dd second];
    return calendarDate;
}

+(NSDate *)calendarToDate:(CalendarDate)calendarDate{
    NSString *dateString = [NSString stringWithFormat:@"%d-%d-%d %d:%d:%d", calendarDate.year, calendarDate.month, calendarDate.day, calendarDate.hour, calendarDate.minute, calendarDate.second];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [dateFormatter dateFromString:dateString];
}

//判断文件是否存在

+(BOOL) fileIsExists:(NSString*) checkFile{
    return  [[NSFileManager defaultManager]fileExistsAtPath:checkFile];
}

#pragma mark 邮箱正则表达式
+(BOOL)validateEmail:(NSString *)email{
    
    NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:email];
    
}


#pragma mark 手机号码正则表达式
+(BOOL)validatePhone:(NSString *)phone{
    NSString *regex = @"^[1][3|5|7|8]\\d{9}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:phone];
}


/**
 *  密码不能含有英文和数字以外的字符
 *  密码必须为6-16位
 */
#pragma mark 密码正则表达式
+ (BOOL)validatePassword:(NSString *)password {
    NSString *regex = @"^[!-~]+$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:password];
}


+(NSString *)createUniqueString{
    NSString *timeStr = [NSUUID UUID].UUIDString;
    NSString *md5Str = [self md5:timeStr];
    return [md5Str substringWithRange:NSMakeRange(0, 24)];
}

+ (NSString *)md5:(NSString *)str{
    if (!str.length) {
        return @"";
    }
    const char *cStr = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    NSMutableString *md5 = [NSMutableString string];
    for (int i = 0; i < 16; i++)
        [md5 appendFormat:@"%02X", result[i]];
    return [md5 uppercaseString];
}

/**
 *  判断是否获取相册权限
 *
 *  @return 是否获取相册权限
 */
+ (BOOL)isGetPhotoLibraryAuthorized {
    if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0f) {
        if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized||[PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusNotDetermined) return YES;
    } else {
        if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusAuthorized || [ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusNotDetermined) return YES;
    }
    return NO;
}

/**
 *  判断是否获取相机权限
 *
 *  @return 是否获取相册权限
 */
+ (BOOL)isGetCameraAuthorized{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusAuthorized || authStatus == AVAuthorizationStatusNotDetermined){
        return YES;
    }
    return NO;
}

/**
 *  验证是否为16进制字符串
 *
 *  @param str 传入字符串
 *
 *  @return 是否是16进制字符串
 */
+ (BOOL)isHexadecimalString:(NSString *)str {
   NSString *regex = @"^[A-Fa-f0-9]+$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:str];
}
@end
